package com.cutefool.zero.code.admin.meta.model.service;

import com.cutefool.core.res.Message;
import com.cutefool.core.res.Response;
import com.cutefool.core.res.ResponseCode;
import com.cutefool.dsl.mybatis.core.dsl.builder.QueryDsl;
import com.cutefool.dsl.mybatis.core.dsl.operation.CuteCurdOperation;
import com.cutefool.zero.code.admin.meta.model.dto.ModelDTO;
import com.cutefool.zero.code.core.domain.Model;
import jakarta.annotation.Resource;
import org.mybatis.dynamic.sql.SqlBuilder;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

@Component
public class ModelService {

    @Resource
    private CuteCurdOperation<Model> cuteCurdOperation;


    public Response<Boolean> validate(Long id, ModelDTO dto) {
        boolean validateName = this.validateName(id, dto.getName());
        if (!validateName) {
            return Response.failure(ResponseCode.API_ERROR.getCode(), String.format(Message.MESSAGE_DATA_EXISTS, dto.getName()));
        }
        boolean validateTableName = this.validateTableName(id, dto.getTableName());

        if (!validateTableName) {
            return Response.failure(ResponseCode.API_ERROR.getCode(), String.format(Message.MESSAGE_DATA_EXISTS, dto.getTableName()));
        }
        return Response.ok();
    }


    public boolean validateName(Long id, String name) {
        QueryDsl<Model> queryDsl = QueryDsl.newInstance(Model.instance(), where -> {
            Model instance = Model.instance();
            where.and(instance.table().name, SqlBuilder.isEqualTo(name));
        });

        Optional<Model> optional = cuteCurdOperation.get(queryDsl);
        return optional.isEmpty() || optional.filter(e -> Objects.equals(e.getId(), id)).stream().findAny().isPresent();


    }

    public boolean validateTableName(Long id, String tableName) {
        QueryDsl<Model> queryDsl = QueryDsl.newInstance(Model.instance(), where -> {
            Model instance = Model.instance();
            where.and(instance.table().tableName, SqlBuilder.isEqualTo(tableName));
        });
        Optional<Model> optional = cuteCurdOperation.get(queryDsl);
        return optional.isEmpty() || optional.filter(e -> Objects.equals(e.getId(), id)).stream().findAny().isPresent();
    }
}
